/*
 * FileVideoFragment.java
 * classes : com.ruint.lib.mediachooser.fragment.FileVideoFragment
 * @author ruint
 * V 1.0.0
 * Create at 2014-12-4 下午3:08:03
 */
package com.ruint.lib.mediachooser.fragment;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;

import com.ruint.core.utils.ui.ToastUtils;
import com.ruint.corelib.R;
import com.ruint.lib.mediachooser.adapter.FileGridAdapter;
import com.ruint.lib.mediachooser.bean.MediaModel;
import com.ruint.lib.mediachooser.core.MediaChooserConstants;

/**
 * com.ruint.lib.mediachooser.fragment.FileVideoFragment
 * 
 * @author ruint <br/>
 *         create at 2014-12-4 下午3:08:03
 */
public class FileVideoFragment extends Fragment implements OnScrollListener {
  private final static Uri MEDIA_EXTERNAL_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
  private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;

  private FileGridAdapter mAdapter;
  private GridView mGridView;
  private Cursor mCursor;
  private int mDataColumnIndex;
  private ArrayList<String> mSelectedItems = new ArrayList<String>();
  private ArrayList<MediaModel> mGalleryModelList;
  private View mView;
  private OnVideoSelectedListener mCallback;

  // Container Activity must implement this interface
  public interface OnVideoSelectedListener {
    public void onVideoSelected(int count);
  }

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
      mCallback = (OnVideoSelectedListener) activity;
    } catch (ClassCastException e) {
      throw new ClassCastException(activity.toString() + " must implement OnVideoSelectedListener");
    }
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
  }

  public static FileVideoFragment newInstance() {
    FileVideoFragment fragment = new FileVideoFragment();
    return fragment;
  }

  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (mView == null) {
      mView = inflater.inflate(R.layout.view_grid_layout_media_chooser, container, false);
      mGridView = (GridView) mView.findViewById(R.id.media_grid);

      if (getArguments() != null) {
        initVideos(getArguments().getString("name"));
      } else {
        initVideos();
      }
    } else {
      ((ViewGroup) mView.getParent()).removeView(mView);
      if (mAdapter == null || mAdapter.getCount() == 0) {
        ToastUtils.showToast(getActivity(), "No media file available.");
      }
    }
    return mView;
  }

  private void initVideos(String bucketName) {

    try {
      final String orderBy = MediaStore.Video.Media.DATE_TAKEN;
      String searchParams = null;
      searchParams = "bucket_display_name = \"" + bucketName + "\"";

      final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Video.Media._ID };
      mCursor = getActivity().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns,
          searchParams, null, orderBy + " DESC");
      setAdapter();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void initVideos() {

    try {
      final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
      // Here we set up a string array of the thumbnail ID column we want to get
      // back
      String[] proj = { MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID };
      mCursor = getActivity().getContentResolver().query(MEDIA_EXTERNAL_CONTENT_URI, proj, null, null,
          orderBy + " DESC");
      setAdapter();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  private void setAdapter() {
    int count = mCursor.getCount();
    if (count > 0) {
      mDataColumnIndex = mCursor.getColumnIndex(MEDIA_DATA);
      // move position to first element
      mCursor.moveToFirst();
      mGalleryModelList = new ArrayList<MediaModel>();
      for (int i = 0; i < count; i++) {
        mCursor.moveToPosition(i);
        String url = mCursor.getString(mDataColumnIndex);
        mGalleryModelList.add(new MediaModel(url, false));
      }

      mAdapter = new FileGridAdapter(getActivity());
      mGridView.setAdapter(mAdapter);
      mAdapter.refresh(mGalleryModelList);
      mGridView.setOnScrollListener(this);
    } else {
      ToastUtils.showToast(getActivity(), "No media file available.");
    }

    mGridView.setOnItemLongClickListener(new OnItemLongClickListener() {

      @Override
      public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        FileGridAdapter adapter = (FileGridAdapter) parent.getAdapter();
        MediaModel galleryModel = (MediaModel) adapter.getItem(position);
        File file = new File(galleryModel.getUrl());
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "video/*");
        startActivity(intent);
        return false;
      }
    });

    mGridView.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // update the mStatus of each category in the adapter
        FileGridAdapter adapter = (FileGridAdapter) parent.getAdapter();
        MediaModel galleryModel = (MediaModel) adapter.getItem(position);

        if (!galleryModel.isSelected()) {
          long size = MediaChooserConstants.ChekcMediaFileSize(new File(galleryModel.getUrl()), true);
          if (size != 0) {
            return;
          }
          if ((MediaChooserConstants.MAX_MEDIA_LIMIT == MediaChooserConstants.SELECTED_MEDIA_COUNT)) {
            ToastUtils.showToast(getActivity(), "Already choosed " + MediaChooserConstants.MAX_MEDIA_LIMIT + " pictures.");
            return;
          }
        }

        // inverse the status
        galleryModel.setSelected(!galleryModel.isSelected());
        adapter.notifyDataSetChanged();

        if (galleryModel.isSelected()) {
          mSelectedItems.add(galleryModel.getUrl());
          MediaChooserConstants.SELECTED_MEDIA_COUNT++;
        } else {
          mSelectedItems.remove(galleryModel.getUrl().trim());
          MediaChooserConstants.SELECTED_MEDIA_COUNT--;
        }

        if (mCallback != null) {
          mCallback.onVideoSelected(mSelectedItems.size());
          Intent intent = new Intent();
          intent.putStringArrayListExtra(MediaChooserConstants.MEDIA_SELECTED_LIST, mSelectedItems);
          getActivity().setResult(Activity.RESULT_OK, intent);
        }

      }
    });

  }

  public void addItem(String item) {
    if (mAdapter != null) {
      MediaModel model = new MediaModel(item, false);
      mGalleryModelList.add(0, model);
      mAdapter.notifyDataSetChanged();
    } else {
      initVideos();
    }
  }

  public FileGridAdapter getAdapter() {
    if (mAdapter != null) {
      return mAdapter;
    }
    return null;
  }

  public ArrayList<String> getSelectedVideoList() {
    return mSelectedItems;
  }

  @Override
  public void onScrollStateChanged(AbsListView view, int scrollState) {
    if (view == mGridView) {
      if (scrollState == SCROLL_STATE_FLING) {
        // chk do nothing
      } else {
        mAdapter.notifyDataSetChanged();
      }
    }
  }

  @Override
  public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
  }
}
